package com.shop.util;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import com.shop.domain.Goods;
import com.shop.enumeration.ConditionParam;

/**
 * 根据id定义搜索List的排序规则
 * 
 * @author wenjuanhenxing
 * @version V1.0 ComparatorMap.java 2016-4-2 下午6:02:12
 */
public class ComparatorMap {
	private static Map<String, Comparator<Goods>> listComparator = new HashMap<String, Comparator<Goods>>();
	static {
		listComparator.put(ConditionParam.PRICE_ASC.getCode(),
				new Comparator<Goods>() {

					@Override
					public int compare(Goods o1, Goods o2) {
						// double 价格equal
						if (Math.abs(o1.getPrice() - o2.getPrice()) < 0.0001) {
							return o1.getId() < o2.getId() ? -1 : 1;
						}
						return o1.getPrice() < o2.getPrice() ? -1 : 1;
					}

				});

		listComparator.put(ConditionParam.PRICE_DESC.getCode(),
				new Comparator<Goods>() {

					@Override
					public int compare(Goods o1, Goods o2) {
						// double 价格equal
						if (Math.abs(o1.getPrice() - o2.getPrice()) < 0.0001) {
							return o1.getId() < o2.getId() ? -1 : 1;
						}
						return o1.getPrice() > o2.getPrice() ? -1 : 1;
					}

				});
		// 人气热门（收藏数）
		listComparator.put(ConditionParam.HOT.getCode(),
				new Comparator<Goods>() {

					@Override
					public int compare(Goods o1, Goods o2) {

						return o1.getCollectCnt() > o2.getCollectCnt() ? -1 : 1;
					}

				});
		// 时间倒序
		listComparator.put(ConditionParam.RECENT.getCode(),
				new Comparator<Goods>() {

					@Override
					public int compare(Goods o1, Goods o2) {

						return o1.getRecentUpdate().compareTo(
								o2.getRecentUpdate()) == 1 ? -1 : 1;
					}

				});
	}

	public static Comparator<Goods> getByCode(String code) {
		return listComparator.get(code);
	}
}
